package com.ingrun.tuboshu.service.impl;

import cn.hutool.core.thread.ThreadUtil;
import com.ingrun.tuboshu.entity.SysAdmin;
import com.ingrun.tuboshu.entity.SysUser;
import com.ingrun.tuboshu.entity.vo.PasswordLoginQ;
import com.ingrun.tuboshu.entity.vo.UpdUserQ;
import com.ingrun.tuboshu.service.IAuthService;
import com.ingrun.tuboshu.service.ISysUserService;
import com.ingrun.tuboshu.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class AuthServiceImpl implements IAuthService {

    @Autowired
    private ISysUserService sysUserService;

    @Override
    public String login(PasswordLoginQ query) {
        String username = query.getUsername().trim();
        SysUser dbUser = sysUserService.selectUserByUserName(username);
        if (dbUser == null) {
            ThreadUtil.execAsync(AsyncFactory.recordLogLogin("-1", username, "0", "用户名不正确", StpKit.USER.getLoginType(), MDC.get("tl")));
            throw new ResponseException(ResponseEnum.USERNAME_OR_PASSWORD_ERROR, "用户名不正确");
        }

        if (!dbUser.getStatus().equals("1")) {
            ThreadUtil.execAsync(AsyncFactory.recordLogLogin(dbUser.getId(), username, "0", ResponseEnum.USER_DISABLED_ERROR.getMessage(), StpKit.USER.getLoginType(), MDC.get("tl")));

            throw new ResponseException(ResponseEnum.USER_DISABLED_ERROR);
        }

        if (PasswordUtil.checkPassword(username, query.getPassword(), dbUser.getPassword())) {
            StpKit.USER.login(dbUser.getId());

            dbUser.setPassword(null);
            StpKit.USER.getSession().set("user", dbUser);
            ThreadUtil.execAsync(AsyncFactory.recordLogLogin(dbUser.getId(), username, "1", "登录成功", StpKit.USER.getLoginType(), MDC.get("tl")));
            return StpKit.USER.getTokenValue();
        }

        ThreadUtil.execAsync(AsyncFactory.recordLogLogin(dbUser.getId(), username, "0", "密码校验不通过", StpKit.USER.getLoginType(), MDC.get("tl")));
        throw new ResponseException(ResponseEnum.USERNAME_OR_PASSWORD_ERROR, "密码校验不通过");
    }

    @Override
    public Boolean logout() {
        try {
            String loginIdAsString = StpKit.USER.getLoginIdAsString();
            StpKit.USER.logout();

            log.info("用户{}退出登录", loginIdAsString);
        } catch (Exception ignored) {
        }
        return true;
    }

    @Override
    public SysUser getLoginUserInfo() {
        return (SysUser) StpKit.USER.getSession().get("user");
    }

    @Override
    public Boolean updateSelfUserInfo(UpdUserQ query) {
        return sysUserService.updateSelfUserInfo(query);
    }


}
